import frappe
from frappe.query_builder.functions import IfNull
from erpnext.controllers.accounts_controller import get_taxes_and_charges

# 当选择父级会计科目时自动编码
def generate_account_number(doc, method):
    if doc.is_new() and doc.parent_account and not doc.account_number:
        data=frappe.get_all('Account',filters={'parent_account':doc.parent_account},fields=['account_number'],order_by='account_number')
        child_account_numbers={row.account_number for row in data if row.account_number}

        parent_account_number=frappe.db.get_value('Account',doc.parent_account,'account_number')
        account_number=str(parent_account_number or '')+'01'

        # 如果有99个科目则不允许在创建下级
        if len(data)<98 :     
            # 创建科目编码如果在当前列表中不存在则就是为要新建的科目的代码
            while(account_number  in child_account_numbers):
                account_number=str(int(account_number)+1)
            
            doc.account_number=account_number
            doc.autoname()
            
        else:
            frappe.throw(msg="该父科目下不允许创建超过99个科目",title="提示")


def stock_entry_validate(doc, method):
    set_masterial_issue_expense_account(doc)
    set_manufacture_production_cost_account(doc)


def set_masterial_issue_expense_account(doc):
    if (doc.stock_entry_type == 'Material Issue' or doc.stock_entry_type == 'Material Receipt') and doc.custom_reason:
        expense_account = doc.custom_opposite_account
        if expense_account:
            for row in doc.items:
                row.expense_account = expense_account

# 设置生产入库单上对应的费用科目（方法二）
# Production Input Account 500101 - 生产成本-基本生产成本 - F
# Production Output Account 500103 - 生产成本-基本生产成本结转 - F
def set_manufacture_production_cost_account(doc):
    if doc.stock_entry_type == 'Manufacture':
        production_input_account, production_output_account = frappe.db.get_value('Company',
            doc.company, ['production_input_account', 'production_output_account'])
        if production_input_account or production_output_account:
            for row in doc.items:
                if row.is_finished_item and production_output_account:
                    row.expense_account = production_output_account
                elif row.s_warehouse and production_input_account:
                    row.expense_account = production_input_account


# 手工修改发票税额
def set_taxes_and_charges_po(doc, method):
    if not  doc.taxes:return
    meta=frappe.get_meta(doc.taxes[0].doctype)
    if meta.has_field("actual_tax_amount"):
        is_actual_tax_amount=False
        total_tax_amount=0.0
        for item in doc.taxes:
            if item.actual_tax_amount:
                item.tax_amount=item.actual_tax_amount
                item.base_tax_amount_after_discount_amount=item.actual_tax_amount*doc.conversion_rate
                is_actual_tax_amount=True
            total_tax_amount=total_tax_amount+item.tax_amount
        
        if is_actual_tax_amount:
            doc.taxes_and_charges_added=total_tax_amount
            doc.total_taxes_and_charges=total_tax_amount-doc.taxes_and_charges_deducted
            doc.base_taxes_and_charges_added=total_tax_amount*doc.conversion_rate
            doc.base_total_taxes_and_charges=doc.base_taxes_and_charges_added-doc.base_taxes_and_charges_deducted

# 手工修改发票税额
def set_taxes_and_charges_so(doc, method):
    if  not doc.taxes :return
    meta=frappe.get_meta(doc.taxes[0].doctype)
    if meta.has_field("actual_tax_amount"):
        is_actual_tax_amount=False
        total_tax_amount=0.0
        for item in doc.taxes:
            if item.actual_tax_amount:
                item.tax_amount=item.actual_tax_amount
                item.base_tax_amount_after_discount_amount=item.actual_tax_amount*doc.conversion_rate
                is_actual_tax_amount=True
            total_tax_amount=total_tax_amount+item.tax_amount
        
        if is_actual_tax_amount:
            doc.total_taxes_and_charges=total_tax_amount
            doc.base_total_taxes_and_charges=total_tax_amount*doc.conversion_rate





